import React from 'react'
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { Toast, NavBar, Cell, Input, hooks, Button, Dialog } from 'react-vant';
import { checkTel } from '../../api';
import { saveTel } from '../../store/userSlice';

export default function Step1() {

    let navigate = useNavigate()
    let dispatch = useDispatch()
    const [state, updateState] = hooks.useSetState({
        tel: '',
    })
    console.log(state);

    function isValidPhone(phone) {
        const reg = /^1[3|4|5|7|8][0-9]{9}$/;
        return reg.test(phone);
    }

    function goToRegistStep2() {
        navigate('/regist/step2');
    }

    const Next = () => {
        checkTel({ tel: state.tel }).then(res => {
            console.log(res);
            if (res.data.code === '200') {
                saveTel(dispatch(saveTel(state.tel)))
                Dialog.confirm({
                    title: '提示',
                    message: '将向手机号' + state.tel + '发送短信验证码',
                    onClosed: goToRegistStep2
                })
            } else {
                Toast('手机号已被注册')
            }
        })
    }

    return (
        <div>
            <NavBar
                title="京东注册"
                leftText="返回"
                onClickLeft={() => Toast('返回')}
            />

            <Cell>
                <Input
                    value={state.tel}
                    type='tel'
                    onChange={tel => updateState({ tel })}
                    placeholder='请输入手机号'
                />
            </Cell>

            {!isValidPhone(state.tel) && <Button disabled round type='info'>
                下一步
            </Button>}
            {isValidPhone(state.tel) && <Button round type='info' onClick={Next}>
                下一步
            </Button>}
        </div>
    )
}
